<template>
  <div class="query-plan h-full">
    <div v-if="executing" class="executing-state">
      <div class="flex items-center justify-center h-32">
        <div class="loading-spinner mr-2"></div>
        <span class="text-gray-600">正在分析查询计划...</span>
      </div>
    </div>
    
    <div v-else-if="plan" class="plan-content h-full">
      <div v-if="plan.error" class="error-result">
        <el-alert
          :title="plan.error"
          type="error"
          :closable="false"
          show-icon
        />
      </div>
      
      <template v-else>
        <!-- 执行计划统计信息 -->
        <div class="plan-stats p-4 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
          <div class="plan-info">
            <h3 class="text-sm font-bold text-gray-700 mb-1">查询执行计划</h3>
            <div class="flex items-center space-x-4">
              <span class="text-xs text-gray-500">
                估计总成本: <span class="text-blue-600 font-medium">{{ plan.totalCost || 'N/A' }}</span>
              </span>
              <span class="text-xs text-gray-500">
                估计行数: <span class="text-blue-600 font-medium">{{ plan.rows || 'N/A' }}</span>
              </span>
              <span class="text-xs text-gray-500">
                估计执行时间: <span class="text-blue-600 font-medium">{{ formatDuration(plan.time) }}</span>
              </span>
            </div>
          </div>
          
          <div class="plan-actions flex items-center space-x-2">
            <el-radio-group v-model="viewMode" size="small">
              <el-radio-button label="tree">树状图</el-radio-button>
              <el-radio-button label="table">表格视图</el-radio-button>
              <el-radio-button label="raw">原始数据</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        
        <!-- 执行计划内容 -->
        <div class="plan-body h-[calc(100%-72px)] p-4 overflow-auto">
          <!-- 树状视图 -->
          <div v-if="viewMode === 'tree'" class="plan-tree">
            <el-tree
              :data="planTreeData"
              :props="treeProps"
              :expand-on-click-node="false"
              default-expand-all
              node-key="id"
              class="plan-tree-component"
            >
              <template #default="{ data }">
                <div class="tree-node p-1">
                  <div class="font-medium">{{ data.name }}</div>
                  <div class="text-xs text-gray-500" v-if="data.details">
                    <div v-for="(value, key) in data.details" :key="key" class="detail-item">
                      <span class="detail-key">{{ formatKey(key) }}:</span>
                      <span class="detail-value">{{ formatValue(key, value) }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
          
          <!-- 表格视图 -->
          <div v-else-if="viewMode === 'table'" class="plan-table">
            <el-table
              :data="planTableData"
              stripe
              border
              style="width: 100%"
              max-height="calc(100vh - 300px)"
            >
              <el-table-column prop="operation" label="操作" min-width="150" />
              <el-table-column prop="type" label="类型" min-width="120" />
              <el-table-column prop="rows" label="行数" min-width="80" sortable />
              <el-table-column prop="cost" label="成本" min-width="80" sortable />
              <el-table-column prop="filters" label="过滤条件" min-width="200" show-overflow-tooltip />
              <el-table-column prop="details" label="详情" min-width="200">
                <template #default="scope">
                  <el-popover
                    placement="top"
                    trigger="hover"
                    :width="400"
                  >
                    <template #reference>
                      <el-button link type="primary">详情</el-button>
                    </template>
                    <div>
                      <div v-for="(value, key) in scope.row.rawDetails" :key="key" class="detail-item text-xs py-1">
                        <span class="detail-key font-medium">{{ formatKey(key) }}:</span>
                        <span class="detail-value">{{ formatValue(key, value) }}</span>
                      </div>
                    </div>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 原始数据视图 -->
          <div v-else class="plan-raw">
            <pre class="bg-gray-100 p-4 rounded text-sm font-mono whitespace-pre-wrap">{{ JSON.stringify(plan.raw, null, 2) }}</pre>
          </div>
        </div>
      </template>
    </div>
    
    <div v-else class="no-plan text-center py-8">
      <el-icon class="text-4xl text-gray-400 mb-2"><DataAnalysis /></el-icon>
      <p class="text-gray-500">执行查询后将自动分析执行计划</p>
      <p class="text-sm text-gray-400 mt-2">支持 MySQL/PostgreSQL/SQL Server</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  plan: {
    type: Object,
    default: null
  },
  executing: {
    type: Boolean,
    default: false
  }
})

// 视图模式：树/表格/原始数据
const viewMode = ref('tree')

// 树形组件配置
const treeProps = {
  label: 'name',
  children: 'children'
}

// 格式化执行计划为树形结构
const planTreeData = computed(() => {
  if (!props.plan || !props.plan.nodes) {
    return []
  }
  
  // 递归构建树
  function buildTree(node, id = '0') {
    const treeNode = {
      id,
      name: node.operation || 'Unknown',
      details: {
        type: node.type,
        rows: node.rows,
        cost: node.cost,
        ...node.details
      }
    }
    
    if (node.children && node.children.length > 0) {
      treeNode.children = node.children.map((child, index) => 
        buildTree(child, `${id}-${index}`)
      )
    }
    
    return treeNode
  }
  
  return [buildTree(props.plan.nodes)]
})

// 格式化执行计划为表格结构
const planTableData = computed(() => {
  if (!props.plan || !props.plan.nodes) {
    return []
  }
  
  const tableData = []
  
  // 递归展平节点
  function flattenNodes(node, level = 0) {
    const indent = '  '.repeat(level)
    
    tableData.push({
      operation: `${indent}${node.operation || 'Unknown'}`,
      type: node.type || '',
      rows: node.rows || 0,
      cost: node.cost || 0,
      filters: node.filters || '',
      rawDetails: node.details || {},
      details: Object.entries(node.details || {})
        .map(([key, value]) => `${key}: ${value}`)
        .join(', ')
    })
    
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => flattenNodes(child, level + 1))
    }
  }
  
  flattenNodes(props.plan.nodes)
  
  return tableData
})

// 格式化显示键名
const formatKey = (key) => {
  return key
    .replace(/_/g, ' ')
    .replace(/\b\w/g, l => l.toUpperCase())
}

// 格式化值显示
const formatValue = (key, value) => {
  if (value === null || value === undefined) {
    return 'N/A'
  }
  
  if (key.includes('cost') || key.includes('time')) {
    return typeof value === 'number' ? value.toFixed(2) : value
  }
  
  return value
}

// 格式化时间
const formatDuration = (duration) => {
  if (!duration) return 'N/A'
  
  if (typeof duration === 'number') {
    if (duration < 1000) {
      return `${Math.round(duration)}ms`
    } else {
      return `${(duration / 1000).toFixed(2)}s`
    }
  }
  
  return duration.toString()
}
</script>

<style scoped>
.plan-tree-component {
  font-family: 'JetBrains Mono', monospace;
}

.tree-node {
  font-family: 'JetBrains Mono', monospace;
}

.detail-item {
  display: flex;
  margin: 2px 0;
}

.detail-key {
  min-width: 100px;
  color: #666;
  margin-right: 8px;
}

.detail-value {
  color: #1890ff;
  font-weight: 500;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #e5e7eb;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 